package com.j.lemon.learn.basic.ratelimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

/**
 * @Author lijunjun
 * @Date 2018-12-26 09:45
 * @Description
 */
public class RateLimiterTest {
    public static void main(String[] args) throws InterruptedException {
//        testNoRateLimiter();
        testWithRateLimiter();
//        simple();
    }

    public static void testNoRateLimiter() {

        RateLimiter rateLimiter = RateLimiter.create(5,1000, TimeUnit.MILLISECONDS);
        Long start = System.currentTimeMillis();
//        for (int i = 0; i < 100; i++) {
//            double acquire = rateLimiter.acquire();
//            System.out.println(acquire);
//            System.out.println("call execute.." + i);
//
//        }
//        System.out.println(rateLimiter.acquire(10));
        System.out.println(rateLimiter.acquire());
        System.out.println(rateLimiter.acquire());
        System.out.println(rateLimiter.acquire());
        System.out.println(rateLimiter.acquire());
        Long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

    public static void testWithRateLimiter() {
        Long start = System.currentTimeMillis();
        RateLimiter limiter = RateLimiter.create(10.0); // 每秒不超过10个任务被提交
        for (int i = 0; i < 10; i++) {
            double acquire = limiter.acquire();// 请求RateLimiter, 超过permits会被阻塞
            System.out.println(acquire);
            System.out.println("call execute.." + i);

        }
        Long end = System.currentTimeMillis();

        System.out.println(end - start);

    }


    public static void simple() throws InterruptedException {
        RateLimiter limiter = RateLimiter.create(2);
        //模拟高并发突发消费情况，这种情况是允许的，可能会出现的。
        System.out.println(limiter.acquire(5));
        System.out.println(limiter.acquire());
        System.out.println(limiter.acquire());
        System.out.println(limiter.acquire());

        System.out.println(limiter.acquire());
        System.out.println(limiter.acquire());
    }

}
